<template>
  <view class="local-popup stepper-row">
    <u-popup :round="16" :show="onShow" :close-on-click-overlay="false" mode="bottom" border-radius="10" bgColor="#f6f6f6">
      <view class="popup-content">
        <view class="title-bar">
          <view class="title-text">提交订单</view>
          <view class="close-icon" @click="handleClose">
            <u-icon size="30" name="close" color="#000"></u-icon>
          </view>
        </view>
        <view class="content-area">
          <view class="product-info">
            <view class="product-image">
              <image :src="subOrderData && subOrderData.icon && subOrderData.icon.includes('https') ? subOrderData.icon : imgurl + subOrderData.icon" class="border-radius" mode=""></image>
            </view>
            <view class="product-details">
              <view class="product-name">{{ subOrderData.name }}</view>
              <view class="activity-name">{{ subOrderData.ebMerActivityName }}</view>
            </view>
          </view>
          <view style="background-color: #fff; border-radius: 20rpx; padding: 20rpx; margin-top: 20rpx">
            <view class="quantity-row">
              <view class="quantity-label">商品数量</view>
              <view class="quantity-stepper">
                <u-number-box :min="1" button-size="46" v-model="buyNumber" @change="onChangeNumber" integer :max="subOrderData.purchaseLimit"></u-number-box>
              </view>
            </view>
            <view class="total-price">
              <view class="total-label"
                >商品总价<span class="total-count">(共{{ buyNumber }}件)</span></view
              >
              <view class="total-value">￥{{ allPrice }}</view>
            </view>
            <u-line margin="30rpx 0"></u-line>
            <!-- 有折扣方式显示 -->
            <view class="discount-row">
              <view class="discount-label">折扣方式</view>
              <view class="discount-type">{{ discountData.typeName }}</view>
            </view>
            <view class="remaining-points" v-if="discountData.type && userInfo.isComunityVip == 1">
              <view class="points-label">剩余补贴</view>
              <view class="points-value">{{ jifen }}</view>
            </view>
            <u-line margin="30rpx 0"></u-line>
            <!-- <view class="address-row" v-if="discountData.type === 2">
            <view class="address-label">请选择房屋信息</view>
            <view class="address-value" @click="handleOpenAddress">
              <span>{{ discountData.address }}</span>
              <u-icon name="arrow-right"></u-icon>
            </view>
          </view> -->

            <view class="final-price" style="display: flex; flex-direction: column; align-items: flex-end">
              <view class="final-label">
                <span style="display: block; color: #999999; font-size: 12px">最大折扣{{ startJifen }}补贴</span>
                <span v-if="discountData.type && userInfo.isComunityVip == 1">{{ formData.comunityIntegralUse || 0 }}补贴 抵扣￥{{ formData.comunityIntegralDeduction }}</span>
              </view>
            </view>
            <view class="remaining-points" v-if="discountData.type">
              <view class="points-label">折扣后补贴余额</view>
              <view class="points-value">{{ jifen - formData.comunityIntegralUse >= 0 ? (jifen - formData.comunityIntegralUse).toFixed(2) : 0 }}</view>
            </view>
            <u-line margin="30rpx 0"></u-line>
            <span style="display: flex; align-items: center; justify-content: flex-end"
              >小计<span style="font-size: 20px; color: #fa642f; font-weight: bold"
                >￥{{ userInfo.isComunityVip == 1 ? (allPrice - formData.comunityIntegralDeduction).toFixed(2) : Number(allPrice).toFixed(2) }}</span
              ></span
            >
            <view class="points-return" v-if="userInfo.isComunityVip != 1">
              <view class="return-label">现金返利</view>
              <view class="return-value">{{ integralGive }}</view>
            </view>
          </view>
          <view style="display: flex; align-items: center; justify-content: start" v-if="formData.userConsumeFirst">
            <image style="width: 50rpx; height: 50rpx" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/06/23/首次购_20250623103201A002.png"> </image>
            <view style="margin-left: 10rpx; font-size: 12px; letter-spacing: 2px">本单为首次购买优惠订单 </view>
          </view>
        </view>
        <!-- <view style="font-weight: bold; margin: 10px 0">备注</view> -->

        <view class="placeholder">
          <!-- <u-textarea v-model="remarkssss" placeholder="请输入内容" count autoHeight :maxlength="60" :disabled="merIddd == '1751873058997917' ? true : false"></u-textarea> -->
        </view>
        <view class="footer-bar">
          <view class="footer-left">
            <view class="total-label">合计￥{{ userInfo.isComunityVip == 1 ? (allPrice - formData.comunityIntegralDeduction).toFixed(2) : Number(allPrice).toFixed(2) }}</view>
            <view class="discount-label">共{{ buyNumber }}件，已优惠￥{{ userInfo.isComunityVip == 1 ? formData.comunityIntegralDeduction : 0 }}</view>
          </view>
          <view class="footer-right">
            <button
              :loading="buttonLoading"
              :disabled="buttonLoading"
              style="background-color: #fa642f; width: 90%; height: 40px; border-radius: 10px; color: white; border-radius: 20px; display: flex; align-items: center; justify-content: center"
              @click="onSubmit"
            >
              立即抢购
            </button>
          </view>
        </view>
      </view>
    </u-popup>
    <discount ref="discount" :formData="formData" @getInfo="getInfo"></discount>
  </view>
</template>

<script>
import discount from "./discount.vue";
import { discountMethod, submitOrder, localLifePayment, orderVerification, toBeUsedOrPay, findUserFirst } from "../../../utils/api/local";
import getOrderPay from "../../../utils/api/getOrderPay.js";
import { IMG_URL } from "../../../config/index";
import { getUserInfo } from "../../../utils/request_api.js";
export default {
  mixins: [getOrderPay],
  components: {
    discount,
  },
  props: {
    subOrderData: {
      type: Object,
      default: () => {},
    },
    merIddd: {
      type: String,
      default: "",
    },
    ebMerActivityTicketId: "",
    ebMerActivityId: "",
  },
  computed: {
    // allPrice() {
    //   let number = Number(this.buyNumber || 1);
    //   let price = Number(this.subOrderData.price || 0);
    //   return (number * price).toFixed(2);
    // },
    // discountPrice() {
    //   let discount = Number(this.discountData.price || 0);
    //   return discount.toFixed(2);
    // },
    integralGive() {
      let number = (this.subOrderData.integralGive || 0) * this.buyNumber;
      return number.toFixed(2);
    },
  },
  data() {
    return {
      remarkssss: "",
      imgurl: IMG_URL,
      userInfo: uni.getStorageSync("userInfo") || {},
      jifen: 0,
      onShow: false,
      buyNumber: 1,
      startJifen: 0,
      discountData: {
        type: 0,
        typeName: "",
        comunityIntegralDeduction: "",
        comunityIntegralUse: "",
        consumeIntegraBalance: "",
        consumeIntegralDeduction: "",
        consumeIntegralUse: "",
        frontComunityInteralPoVoList: [],
      },
      formData: { frontComunityInteralPoVoList: [] },
      buttonLoading: false,
      orderType: "pay_ls",
      price: "",
      allPrice: 0.0 /** 商品总价 保留两位小数 */,
    };
  },
  // onReady() {
  //   //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
  //   this.$refs.$uForm.setRules(this.myrules);
  // },

  methods: {
    /** 步数器更改 */
    onChangeNumber(val) {
      // 修改点1：直接使用事件回调值，避免异步问题
      // u-number-box的change事件参数val包含{value, step}
      const currentValue = Number(val.value) || 1; // 获取当前最新值
      let price = Number(this.subOrderData.price || 0);

      // ：立即更新buyNumber的值
      this.buyNumber = currentValue;

      // 使用最新值计算总价
      this.allPrice = (currentValue * price).toFixed(2);

      // 传递最新计算值
      this.getPrice(this.allPrice);
    },
    getPrice(val) {
      /**
       * 平台积分抵扣
       * 1.根据输入金额计算最大可抵扣金额
       * 2.根据抵扣金额计算需扣除补贴
       */
      let gpWyPaymentAmount = Number(this.userInfo.gpWyPaymentAmount || 0);
      if (Number(this.formData.wuyejifenRmbExchangeBili || 0)) {
        let maxComunityPrice =
          this.formData.userConsumeFirst && this.formData.integralComunityDiscountFirst
            ? val * (this.formData.integralComunityDiscountFirst || 0)
            : val * (this.formData.integralComunityDiscountBili || 0);
        //  let maxComunityPrice = val * (this.formData.integralComunityDiscountBili || 0);
        this.startJifen = (maxComunityPrice / this.formData.wuyejifenRmbExchangeBili).toFixed(2); //商品初始全部补贴
        /** 当前补贴最大可抵扣金额 */
        let integraComunityPrice = gpWyPaymentAmount * this.formData.wuyejifenRmbExchangeBili;
        200;
        if (maxComunityPrice > integraComunityPrice) {
          this.formData.comunityIntegralUse = gpWyPaymentAmount.toFixed(2);
          this.formData.comunityIntegralDeduction = integraComunityPrice.toFixed(2);
        } else {
          this.formData.comunityIntegralUse = (maxComunityPrice / this.formData.wuyejifenRmbExchangeBili).toFixed(2);
          this.formData.comunityIntegralDeduction = maxComunityPrice.toFixed(2);
        }
      } else {
        this.formData.comunityIntegralUse = 0.0;
        this.formData.comunityIntegralDeduction = 0.0;
      }

      this.$refs.discount.getInfo(this.discountData.type);
    },
    async handleOpen(id, yaoiqngID) {
      this.yaoiqngID = yaoiqngID;
      this.iddds = id;
      var user = await getUserInfo();
      if (user.code == 401) {
        uni.showToast({
          title: "您的登录已过期，请重新登录",
          icon: "none",
        });
        return;
      } else {
        uni.setStorageSync("userInfo", user.data);
        this.userInfo = user.data;
      }
      this.onShow = true;
      try {
        await this.discountMethod(id);
        // if (Number(this.startJifen) > Number(this.userInfo.gpWyPaymentAmount)) {
        //   uni.showModal({
        //     title: "提示",
        //     content: "补贴余额不足以达到最高折扣金额，是否前往缴纳物业费获取补贴？",
        //     confirmText: "前往",
        //     cancelText: "取消",
        //     success: (res) => {
        //       if (res.confirm) {
        //         uni.navigateTo({
        //           url: "/pages/integral/points-refund/comunity-integral",
        //         });
        //       }
        //     },
        //   });
        // }
      } catch (e) {
        console.error("补贴信息加载失败", e);
        this.$toast("补贴信息加载失败，请稍后再试");
      }
    },
    handleClose() {
      this.onShow = false;
    },
    getInfo(data) {
      this.discountData = data;
    },
    // getAddress(data) {
    //   this.discountData.accumulationFund = data.accumulationFund || 0;
    //   this.discountData.ebComunityHouseId = data.ebComunityHouseId;
    //   this.discountData.address = data.address;
    // },
    onChange(type) {
      this.orderType = type;
    },
    async onSubmit() {
      try {
        if (this.iddds == 338) {
          var res1 = await findUserFirst({ userId: uni.getStorageSync("uid") });
          if (!res1) {
            uni.showToast({ title: "优惠产品，只能购买一次", icon: "none" });
            return;
          }
        }

        const deductionOrdersPrice = this.userInfo.isComunityVip == 1 ? (this.allPrice - this.formData.comunityIntegralDeduction).toFixed(2) : Number(this.allPrice).toFixed(2);
        // if (this.orderType === "pay_yue" && Number(this.userInfo.nowMoney || 0) < deductionOrdersPrice) {
        //   this.$toast("账户余额不足，请先充值");
        //   return;
        // }
        this.buttonLoading = true;
        let that = this;
        let params = {
          ebUserId: uni.getStorageSync("uid"),
          ebMerActivityTicketId: this.ebMerActivityTicketId,
          ebMerActivityId: this.ebMerActivityId,
          deductionPrice: this.formData.comunityIntegralDeduction,
          deductionType: this.discountData.type,
          gainIntegral: this.userInfo.isComunityVip != 1 ? this.integralGive : 0.0,
          isChannel: this.orderType === "pay_ls" ? 6 : 1,
          make: "",
          payPrice: deductionOrdersPrice,
          payType: "lszfxcx",
          proTotalPrice: this.allPrice,
          totalNum: this.buyNumber,
          totalPrice: this.subOrderData.price,
          useIntegralComunity: this.userInfo.isComunityVip == 1 ? this.formData.comunityIntegralUse : 0.0,
          useIntegralConsume: this.discountData.type == 1 ? this.discountData.discount : 0.0,
          ebComunityHouseId: this.discountData.ebComunityHouseId,
          orderType: 2,
          remark: this.subOrderData.remark,
          payWatercardInviteUserId: this.yaoiqngID || this.subOrderData.ebUserId,
          businessId: this.merIddd,
          dealEbMerId: this.merIddd,
        };
        if (this.subOrderData.isLaundry == 0) {
          params.orderType = 7;
        }
        submitOrder(params).then((res) => {
          console.log("submitOrder" + res);
          var pae = {
            uni: res.data.id,
            orderNo: res.data.orderId,
            payChannel: "public",
            payType: "lszfxcx",
            scene: 0, //下单时小程序的场景值
          };
          localLifePayment(pae).then((obj) => {
            console.log("localLifePayment" + obj);
            if (obj.code == 200) {
              uni.requestPayment({
                timeStamp: obj.data.jsConfig.timeStamp, //后端返回的时间戳
                nonceStr: obj.data.jsConfig.nonceStr, //后端返回的随机字符串
                package: obj.data.jsConfig.packages, //后端返回的prepay_id
                signType: "RSA", //后端签名算法,根据后端来,后端MD5这里即为MD5
                paySign: obj.data.jsConfig.paySign, //后端返回的签名
                payCompletedPageOptions: {
                  showNavBackButton: true,
                },
                success(resdw) {
                  uni.hideLoading();
                  console.log("订单支付完成！" + resdw);
                  resdw.payCompletedPage.onUnload((dawd) => {
                    setTimeout(() => {
                      if (that.subOrderData.isAuto == 1) {
                        let ticketCode;
                        toBeUsedOrPay({ orderId: res.data.orderId }).then((res) => {
                          if (res && res.code === 200) {
                            ticketCode = res.data.ebMerActivityTicketRecordList[0].ticketCode || [];
                            orderVerification({
                              ticketCode: ticketCode,
                              userId: 63,
                            }).then((res) => {
                              that.onShow = false;
                              if (res.code) {
                                uni.switchTab({
                                  url: "/pages_h5/index/index",
                                });
                              }
                            });
                          }
                        });
                        uni.showToast({
                          title: "订单支付成功",
                          icon: "success",
                        });
                      } else {
                        uni.redirectTo({
                          url: `/pages_h5/local_life/components/order_detail?status=1&orderId=${res.data.orderId}&id=${res.data.id}`,
                          complete(err) {
                            console.log(err);
                          },
                        });
                      }
                    }, 500);
                  });
                },
                fail(resdw) {
                  console.log("🚀取消支付", resdw);
                  uni.hideLoading();
                  setTimeout(() => {
                    console.log(res.data.orderId);
                    // uni.switchTab({
                    //   url: "/pages_h5/index/index", // 点击左上角返回按钮，会触发支付回调页onUnload 事件，在 onUnload 事件触发时可以跳转到别的页面
                    // });
                    uni.redirectTo({
                      url: `/pages_h5/local_life/components/order_detail?status=1&orderId=${res.data.orderId}&id=${res.data.id}&status=0`,
                      complete(err) {
                        console.log(err);
                      },
                    });
                  }, 500);
                },
              });
              this.buttonLoading = false;
            } else {
              uni.showToast({
                title: "下单失败了，请稍后再试",
                icon: "none",
              });
              this.buttonLoading = false;
            }
          });
          // let goPagesSuccess = `/pages_h5/local_life/components/order_detail?status=1&orderId=${res.data.orderId}&id=${res.data.id}`;
          // let goPagesFail = `/pages_h5/local_life/components/order_detail?status=0&orderId=${res.data.orderId}&id=${res.data.id}`;
          // this.getOrderPay({
          //   id: res.data.id,
          //   orderNo: res.data.orderId,
          //   tab: 5,
          //   goPagesSuccess,
          //   goPagesFail,
          // });
          // uni.request({
          //   url: "https://www.wantongkonggu.cn/api/frontApph7/order/get/pay/lsReceipt",
          //   method: "GET",
          //   data: { leshuaOrderId: leshua },
          //   success: (resd) => {
          //     uni.request({
          //       url: "https://www.wantongkonggu.cn/api/frontApph7/pay/LsQueryPayResult",
          //       method: "GET",
          //       data: { orderNo: resd.data.data.orderId },
          //       success(ressss) { },
          //     });
          //   },
          //   fail: (err) => {
          //     that.errdata = JSON.stringify(err);
          //   },
          //   complete: (ress) => { },
          // });
        });
      } catch (error) {
        uni.showToast({
          title: "请求失败",
          icon: "none",
          duration: 2000,
        });
      } finally {
      }
    },
    async discountMethod(id) {
      try {
        const res = await discountMethod({
          ticket_id: id,
          user_id: uni.getStorageSync("uid"),
        });
        this.formData = res.data || {};
        if (res.data.frontComunityInteralPoVo) {
          this.jifen = res.data.frontComunityInteralPoVo.accumulationFund || 0;
        }
        this.$nextTick(() => {
          let temp = this.formData.frontComunityInteralPoVo != null ? 2 : 0;
          if (temp === 2) {
            if (this.userInfo.isComunityVip != 1) {
              temp = 0;
            }
          }
          this.discountData.type = temp;
          this.onChangeNumber({ value: 1 });
        });
      } catch (error) {
        console.error("折扣方式加载失败", error);
        this.$toast("获取折扣方式失败，请稍后再试");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.border-radius {
  width: 88rpx;
  height: 88rpx;
  border-radius: 20rpx;
}

.local-popup {
  .popup-content {
    padding: 20rpx 30rpx;

    .title-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;

      .title-text {
        font-size: 30rpx;
        font-weight: bold;
      }

      .close-icon {
        cursor: pointer;
      }
    }

    .product-info {
      display: flex;
      margin-top: 20rpx;

      .product-image {
        width: 150rpx;
        height: 150rpx;
        margin-right: 20rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .product-details {
        width: calc(100% - 150rpx - 20rpx);

        .product-name {
          font-size: 30rpx;
          font-weight: bold;
          margin-bottom: 20rpx;
        }

        .activity-name {
          font-size: 26rpx;
          color: #666;
        }
      }
    }

    .quantity-row,
    .total-price,
    .discount-row,
    .remaining-points,
    .final-price,
    .points-return {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20rpx;
    }

    .quantity-label,
    .total-label,
    .discount-label,
    .points-label,
    .final-label,
    .return-label {
      font-size: 14px;
      color: #1a1a1a;
    }

    .quantity-stepper {
      width: 200rpx;
    }

    .total-value,
    .discount-type,
    .points-value,
    .return-value {
      font-size: 26rpx;
      color: #fa642f;
    }

    .total-count {
      font-size: 22rpx;
      color: #999;
    }

    .final-price,
    .points-return {
      margin-top: 10rpx;
    }

    .footer-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx;
      background-color: #fff;
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      padding-bottom: 40rpx;

      .footer-left {
        .total-label {
          font-size: 32rpx;
          font-weight: bold;
          color: #fa642f;
        }

        .discount-label {
          font-size: 26rpx;
          color: #666;
        }
      }

      .footer-right {
        width: 320rpx;
      }
    }

    .placeholder {
      font-size: 26rpx;
      padding: 20rpx;
      // min-height: 220rpx;
      // max-height: 220rpx;
      // background-color: #fff;
      border-radius: 20rpx;
      margin-bottom: 90rpx;
    }
  }
}
</style>
